<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>修改商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示信息 -->
      <el-alert
        title="修改商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps
        :space="200"
        :active="stepActiveIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab 栏区域 -->
      <el-form
        :model="addGoodFrom"
        :rules="addGoodFromRules"
        ref="addGoodFromRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="stepActiveIndex"
          :before-leave="tabBeforeLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodFrom.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="addGoodFrom.goods_price"
                type="number"
                min="0"
                onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="addGoodFrom.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="addGoodFrom.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodFrom.goods_cat"
                :options="categoryList"
                :props="cascaderProps"
                @change="handleChange"
                disabled
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in this.manyGoodParams"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="item"
                  v-for="(item, index) in item.attr_vals"
                  :key="index"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyGoodParams"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadAction"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="goodPicsList"
              list-type="picture"
              :headers="uploadHeaders"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <!-- 图片预览对话框 -->
            <el-dialog
              title="图片预览"
              :visible.sync="previewDialogVisible"
              width="50%"
            >
              <img :src="picPreviewUrl" alt="" class="preview" />
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodFrom.goods_introduce" />
            <el-button
              size="small"
              type="primary"
              class="addBtn"
              @click="addGoodRequest"
              >修改商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  created () {
    this.getCategoryList()
    this.getGoodInfo()
  },
  props: ['id'],
  data () {
    return {
      // 商品 id
      goodId: location.hash.split('/').pop(),
      stepActiveIndex: '0',
      addGoodFrom: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      addGoodFromRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      //   商品分类列表
      categoryList: [],
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //   动态商品参数列表
      manyGoodParams: [],
      //   静态商品参数列表
      onlyGoodParams: [],
      //   上传图片地址
      uploadAction: 'http://127.0.0.1:8888/api/private/v1/upload',
      //   设置上传商品图片请求头
      uploadHeaders: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //   上传图片预览地址
      picPreviewUrl: '',
      //   图片预览对话框开启和关闭
      previewDialogVisible: false,
      //   上传图片列表
      goodPicsList: []
    }
  },
  methods: {
    //   获取商品分类列表
    async getCategoryList () {
      let { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.categoryList = res.data
    },
    // 获取修改商品的信息
    async getGoodInfo () {
      let { data: res } = await this.$http.get('goods/' + this.goodId)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      console.log(res)
      this.addGoodFrom.goods_name = res.data.goods_name
      this.addGoodFrom.goods_weight = res.data.goods_weight
      this.addGoodFrom.goods_number = res.data.goods_number
      this.addGoodFrom.goods_price = res.data.goods_price
      this.addGoodFrom.goods_cat = [
        res.data.cat_one_id,
        res.data.cat_two_id,
        res.data.cat_three_id
      ]
      this.addGoodFrom.goods_introduce = res.data.goods_introduce

      res.data.pics.forEach((V) => {
        let picInfo = {
          name: V.pics_id,
          url: V.pics_mid_url
        }
        this.goodPicsList.push(picInfo)
      })
      this.getManyGoodParams()
      this.getOnlyGoodParams()
    },
    // 商品分类级联选择器选择改变时
    handleChange () {
      if (this.addGoodFrom.goods_cat.length !== 3) {
        this.$message.info('只允许选择第三级分类！')
        this.addGoodFrom.goods_cat = []
      }
    },
    // tab 标签切换前的钩子函数
    tabBeforeLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodFrom.goods_cat.length !== 3) {
        this.$message.info('请选择商品分类')
        return false
      }
    },
    // 获取商品参数
    async getManyGoodParams () {
      let { data: res } = await this.$http.get(
        `categories/${this.addGoodFrom.goods_cat[2]}/attributes`,
        {
          params: {
            sel: 'many'
          }
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach((v) => {
        v.attr_vals = v.attr_vals.trim() ? v.attr_vals.split(' ') : []
      })
      this.manyGoodParams = res.data
    },
    // 获取商品属性
    async getOnlyGoodParams () {
      let { data: res } = await this.$http.get(
        `categories/${this.addGoodFrom.goods_cat[2]}/attributes`,
        {
          params: {
            sel: 'only'
          }
        }
      )
      if (res.meta.status !== 200) return this.$message.errof(res.meta.msg)
      this.onlyGoodParams = res.data
    },
    // 图片预览事件
    handlePreview (file) {
      let picUrl = file.response.data.url
      this.picPreviewUrl = picUrl
      this.previewDialogVisible = true
    },
    // 图片移除事件
    handleRemove (file) {
      let picInfo = file.response.data.tmp_path
      let index = this.addGoodFrom.pics.findIndex((v) => {
        return v.pic === picInfo
      })
      this.addGoodFrom.pics.splice(index, 1)
    },
    // 图片上传成功事件
    handleSuccess (response) {
      let picInfo = { pic: response.data.tmp_path }
      this.addGoodFrom.pics.push(picInfo)
      console.log(this.goodPicsList)
    },
    // 发送添加商品请求
    addGoodRequest () {
      this.$refs.addGoodFromRef.validate(async (valid) => {
        if (!valid) return this.$message.error('请填写必填项')
        let form = _.cloneDeep(this.addGoodFrom)
        form.goods_cat = form.goods_cat.join(',')
        this.manyGoodParams.forEach((item) => {
          let paramsInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          form.attrs.push(paramsInfo)
        })
        this.onlyGoodParams.forEach((item) => {
          let paramsInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          form.attrs.push(paramsInfo)
        })
        let { data: res } = await this.$http.put('goods/' + this.id, form)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('修改商品成功')
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 15px 0 0 !important;
}
.preview {
  width: 100%;
}
.addBtn {
  margin-top: 15px;
}
</style>
